package com.ml4ai.backend.services.mappers;

import com.ml4ai.backend.consts.Const;
import com.ml4ai.backend.domain.Task;
import com.ml4ai.backend.dto.TaskDTO;
import com.ml4ai.backend.repository.SiteRepository;
import com.ml4ai.backend.repository.TaskRepo;
import com.ml4ai.backend.repository.UserRepo;
import com.ml4ai.backend.utils.Bean2Bean;
import com.ml4ai.backend.utils.PropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by uesr on 2018/9/9.
 */
@Component
public class TaskMapper extends BaseMapper<Task, TaskDTO> {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRepo userRepo;

    @Autowired
    TaskRepo taskRepo;

    @Autowired
    SiteMapper siteMapper;

    @Autowired
    SiteRepository siteRepository;

    @Override
    public Task newEntity() {
        return new Task();
    }

    @Override
    public TaskDTO newDTO() {
        return new TaskDTO();
    }

    @Override
    public Task find(Long id) {
        return taskRepo.getOne(id);
    }

    @Override
    public void entity2dto(Task entity, TaskDTO dto) {
        new Bean2Bean().addPropMapper(
                new PropertyMapper<>("starter", userMapper::e2d),
                new PropertyMapper<>("starter.id", "starterId"),
                new PropertyMapper<>("taker", userMapper::e2d),
                new PropertyMapper<>("taker.id", "takerId"),
                new PropertyMapper<>("site", siteMapper::e2d),
                new PropertyMapper<>("site.id", "siteId")
        ).copyProperties(entity, dto);

    }

    @Override
    public void dto2entity(TaskDTO dto, Task entity) {
        new Bean2Bean().addExcludeProp("starter", "taker", "site").addExcludeProp(Const.getNotCopyAuditFields()).copyProperties(dto, entity);

        Long siteId = Bean2Bean.getFirstNoNullVal(dto, "siteId", "site.id");
        if (siteId != null) {
            entity.setSite(siteRepository.getOne(siteId));
        } else {
            entity.setSite(null);
        }
        Long starterId = Bean2Bean.getFirstNoNullVal(dto, "starterId", "starter.id");
        if (starterId != null) {
            entity.setStarter(userRepo.getOne(starterId));
        } else {
            entity.setStarter(null);
        }
        Long takerId = Bean2Bean.getFirstNoNullVal(dto, "takerId", "taker.id");
        if (takerId != null) {
            entity.setTaker(userRepo.getOne(takerId));
        } else {
            entity.setTaker(null);
        }
    }
}
